<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use DB,Session;

class Shopcar extends Model
{
    protected $table = 'cart';
    public $timestamps = false;
    protected $guarded = [];
    
    // 获取购物车数据
    public static function getCartList()
    {
        $uid = Session::get('userData')->id;
        
        // 这里只获取有效的商品信息
        $data = self::leftJoin('goods', 'cart.goods_id', '=', 'goods.id')
                ->where('cart.user_id', $uid)
                ->where('goods.goods_status', 1)
                ->where('goods.goods_num', '>', 0)
                ->where('goods.is_sale', 1)
                ->where('cart.cart_num', '>', 0)
                ->select(["cart.*", "goods.goods_name"])
                ->orderBy('cart.id', 'desc')
                ->get();
        
        return $data;
    }
    
    // 详情页加入购物车
    public static function addCart($data)
    {
        // 获取用户id
        $user_id = Session::get('userData')->id;
        $data['user_id'] = $user_id;
        $data['cart_price'] = DB::table('goods_attr')->where('goods_id', $data['goods_id'])
                ->where('id', $data['attr_id'])
                ->pluck('attr_price');
        $data['cart_img'] = DB::table('goods')->where('id', $data['goods_id'])->pluck('goods_thumb');
        // 判断是否已存在该商品
        $iscar = Shopcar::where('user_id', $data['user_id'])
                ->where('attr_id', $data['attr_id'])
                ->first();
        
        if($iscar){
            // 存在，则只更新数量
            $res = Shopcar::where('id', $iscar->id)->increment('cart_num', $data['cart_num']);
        } else {
            $res = Shopcar::insert($data);
        }
        
        return $res;
    }
    
    // 修改购物车数量
    public static function changeNum($data)
    {
        if ($data["act"] == "inc")
        {
            $res = self::where("id", $data['id'])->increment("cart_num", 1);//数量加1
        } else if ($data['act'] == "dec")
        {
            $res = self::where("id", $data['id'])->decrement("cart_num", 1);//数量减1
        } else //手动修改input标签中的数量
        {
            $res = self::where("id", $data['id'])->update("cart_num", $data['cart_num']);
        }
        
        return $res;
    }
}
